package com.lyz.process;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.apache.log4j.Logger;

/**
 * 文件进度类
 * @author luyongzhao
 *
 */
public class FileProcess {
	
	private static final Logger logger = Logger.getLogger(FileProcess.class);
	
	private RandomAccessFile raf = null;
	
	private String filePath = null;
	/*进度文件中一行记录最大长度*/
	private int maxLength = 0;
	
	public FileProcess(String filePath){
		this.filePath = filePath;
		init();
	}
	
	private void init(){
		File file = new File(this.filePath);
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			
			raf = new RandomAccessFile(file, "rw");
			
		} catch (Exception e) {
			logger.warn("fail to init FileProcess!",e);
		}
	}
	
	public String getProcessInfo(){
		try {
			raf.seek(0);
			String line = raf.readLine();
			if(line != null){
				maxLength = maxLength<line.length()?line.length():maxLength;
			}
			return line==null?null:line.trim();
		} catch (IOException e) {
			logger.warn("fail to get process info!",e);
			return null;
		}
	}
	
	public synchronized void setProcessInfo(String line){
		
		if(line==null || "".equals(line.trim())){
			logger.warn("fail to set process info where line is empty!");
			return;
		}
		try {
			raf.seek(0);
			if (line.length() >= maxLength) {
				raf.writeBytes(line);
				maxLength = line.length();
			} else {
				StringBuffer buffer = new StringBuffer(maxLength);
				buffer.append(line);
				for (int i = line.length(); i < maxLength; i++) {
					buffer.append(" ");
				}
				raf.writeBytes(buffer.toString());
			}

		} catch (IOException e) {
			logger.error("", e);
		}
		
	}
	
	public void close(){
		try {
			if(raf != null){
				raf.close();
				raf = null;
			}
		} catch (IOException e) {
			logger.warn("fail to close process file:"+this.filePath);
		}
	}
	
}
